//
//  CodeBlockView.swift
//  MMarkUI
//
//  Created by nowcoder on 2025/2/18.
//

import UIKit
import SnapKit

class CodeBlockView: UIView {
    
    // MARK: - Properties
    private let codeTextView: UITextView = {
        let textView = UITextView()
        textView.isEditable = false
        textView.isSelectable = true
        textView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        textView.font = UIFont(name: "Menlo", size: 12)
        textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
        textView.layer.cornerRadius = 8
        textView.layer.masksToBounds = true
        return textView
    }()
    
    private let headerView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        view.layer.cornerRadius = 8
        view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
        view.layer.masksToBounds = true
        return view
    }()
    
    private let languageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        label.textColor = UIColor.darkGray
        return label
    }()
    
    private lazy var copyButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(systemName: "doc.on.doc"), for: .normal)
        button.tintColor = UIColor.darkGray
        button.addTarget(self, action: #selector(copyButtonTapped), for: .touchUpInside)
        return button
    }()
    
    // MARK: - Properties
    private var codeText: String
    private var language: String
    
    // MARK: - Initialization
    init(codeText: String, language: String) {
        self.codeText = codeText
        self.language = language
        super.init(frame: .zero)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    private func setupUI() {
        backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        layer.cornerRadius = 8
        layer.masksToBounds = true
        layer.borderWidth = 1
        layer.borderColor = UIColor(white: 0.85, alpha: 1.0).cgColor
        
        // 添加子视图
        addSubview(headerView)
        headerView.addSubview(languageLabel)
        headerView.addSubview(copyButton)
        addSubview(codeTextView)
        
        // 设置约束
        headerView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(36)
        }
        
        languageLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(12)
            make.centerY.equalToSuperview()
        }
        
        copyButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 24, height: 24))
        }
        
        codeTextView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        // 设置内容
        languageLabel.text = language.uppercased()
        codeTextView.text = codeText
        
        // 确保复制按钮可见
        copyButton.isHidden = false
        
        // 确保语言标签可见
        languageLabel.isHidden = false
        
        // 打印调试信息
        print("CodeBlockView 创建: 语言=\(language), 内容长度=\(codeText.count)")
    }
    
    // MARK: - Actions
    @objc private func copyButtonTapped() {
        UIPasteboard.general.string = codeText
        
        // 显示复制成功的反馈
        UIView.animate(withDuration: 0.2, animations: {
            self.copyButton.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
        }) { _ in
            UIView.animate(withDuration: 0.2) {
                self.copyButton.transform = .identity
            }
        }
        
        // 临时更改按钮图标
        let originalImage = copyButton.image(for: .normal)
        copyButton.setImage(UIImage(systemName: "checkmark"), for: .normal)
        
        // 2秒后恢复原始图标
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.copyButton.setImage(originalImage, for: .normal)
        }
    }
    
    // MARK: - Size Calculation
    func calculateHeight(forWidth width: CGFloat) -> CGFloat {
        let headerHeight: CGFloat = 36
        
        // 计算代码文本的高度
        let textWidth = width - 24 // 减去左右内边距
        
        // 计算每行的高度
        let lineHeight: CGFloat = 18 // 估计的行高
        
        // 计算行数
        let lines = codeText.components(separatedBy: .newlines)
        let numberOfLines = max(1, lines.count)
        
        // 计算文本高度
        let textHeight = CGFloat(numberOfLines) * lineHeight + 24 // 加上上下内边距
        
        return headerHeight + textHeight
    }
} 